<template>
  <div class="dashboard-container">
    <div class="app-container">
      <PageTools :show-before="true">
        <template #before> 共{{ params.total }}条记录 </template>
        <template #after>
          <el-button
            size="small"
            type="warning"
            @click="$router.push('/import')"
            >导入</el-button
          >
          <el-button size="small" type="danger" @click="exportExcel"
            >导出</el-button
          >
          <el-button
            v-if="checkPermission('yuangongxiaozu')"
            size="small"
            type="primary"
            @click="showDialog = true"
            >新增员工</el-button
          >
        </template>
      </PageTools>

      <!-- 放置表格和分页 -->
      <el-card>
        <el-table border :data="list">
          <el-table-column label="序号" sortable="" type="index" />
          <el-table-column label="头像" width="200">
            <template #default="{ row }">
              <img
                v-imgerr="require('@/assets/common/head.jpg')"
                :src="row.staffPhoto"
                alt=""
                class="avatar"
                @click="showQRCode(row.staffPhoto)"
              />
            </template>
          </el-table-column>
          <el-table-column prop="username" label="姓名" sortable="" />
          <el-table-column prop="workNumber" label="工号" sortable="" />
          <el-table-column
            prop="formOfEmployment"
            label="聘用形式"
            sortable=""
            :formatter="formatEmployment"
          />
          <el-table-column prop="departmentName" label="部门" sortable="" />
          <el-table-column label="入职时间" sortable="">
            <template #default="{ row }">
              {{ row.timeOfEntry | formatDate }}
            </template>
          </el-table-column>
          <el-table-column label="账户状态" sortable="">
            <template #default="{ row }">
              <!-- {{ row.enableState }} -->
              <el-switch :value="row.enableState === 1" />
            </template>
          </el-table-column>
          <el-table-column label="操作" sortable="" fixed="right" width="280">
            <template #default="{ row }">
              <el-button
                type="text"
                size="small"
                @click="$router.push(`/employees/detail/${row.id}`)"
                >查看</el-button
              >
              <el-button type="text" size="small">转正</el-button>
              <el-button type="text" size="small">调岗</el-button>
              <el-button type="text" size="small">离职</el-button>
              <el-button type="text" size="small" @click="assignRole(row.id)"
                >角色</el-button
              >
              <el-button type="text" size="small" @click="delEmployee(row.id)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row
          type="flex"
          justify="center"
          align="middle"
          style="height: 60px"
        >
          <el-pagination
            layout="prev, pager, next"
            :total="params.total"
            :page-size="params.size"
            @current-change="currentChange"
          />
        </el-row>
      </el-card>
      <AddEmployee
        :showDialog.sync="showDialog"
        @addEmployee="getEmployeeList"
      ></AddEmployee>
      <el-dialog
        title="二维码"
        :visible="isShowQRCode"
        @close="isShowQRCode = false"
      >
        <el-row type="flex" justify="center">
          <canvas ref="myCanvas" />
        </el-row>
      </el-dialog>
      <AssignRole
        :userId="userId"
        ref="assignRole"
        :showDialog.sync="showRoleDialog"
      ></AssignRole>
    </div>
  </div>
</template>

<script>
import AddEmployee from "@/views/employees/components/add-employee.vue";
import { getEmployeeList, delEmployee } from "@/api/employees";
import employeeEnum from "@/api/constant/employees";
import { export_json_to_excel } from "@/vendor/Export2Excel";
import { formatDate } from "@/filters";
import QRCode from "qrcode";
import AssignRole from "@/views/employees/components/assign-role.vue";
export default {
  components: {
    AddEmployee,
    AssignRole,
  },
  // filters: {
  //   formatDate(val) {
  //     // 过滤器在设计当中遵循纯函数概念
  //     // 1. 不依赖当前环境
  //     // 2. 不对当前环境造成影响(副作用)
  //     // 3. 只要输入相同, 执行多少次, 输出都一样
  //     // 所以拿不到this
  //     // console.log('过滤器')
  //     // console.log(this)
  //     return val.split('T')[0]
  //   }
  // },
  data() {
    return {
      showDialog: false,
      list: [],
      params: {
        page: 1,
        size: 5,
        total: 0,
      },
      isShowQRCode: false,
      showRoleDialog: false,
      userId: "",
    };
  },
  created() {
    this.getEmployeeList();
  },
  methods: {
    async getEmployeeList() {
      const { total, rows } = await getEmployeeList(this.params);
      this.params.total = total;
      // 因为本地数据服务器缺少了一个 enableState 属性
      // 这里对所有的员工进行处理, 如果没有这个值就补个1
      this.list = rows.map((v) => {
        return {
          ...v,
          enableState: this.enableState || 1,
        };
      });
    },
    currentChange(newPage) {
      this.params.page = newPage;
      this.getEmployeeList();
    },
    // 列格式化
    formatEmployment(row, col, cell, index) {
      // 这里是格式化函数, 可以得到当前格子的值
      // 这里返回的数据会替代原来的值显示在页面上完成格式化工作
      // 加入聘用形式为1 就是正式工, 聘用形式为2 就是临时工
      // if (cell === 1) return "正式";
      // if (cell === 2) return "非正式";
      const res = employeeEnum.hireType.find((v) => +v.id === +cell);
      return res ? res.value : "未知";
    },

    // 点击导出
    async exportExcel() {
      // 1. 获取所有员工
      const { rows } = await getEmployeeList({
        page: 1,
        size: this.params.total,
      });
      console.log("源数据", rows);

      // 中间进行数据转换
      // 就像之前的导入一样, 给个字典
      const dict = {
        姓名: "username",
        手机号: "mobile",
        入职日期: "timeOfEntry",
        聘用形式: "formOfEmployment",
        转正日期: "correctionTime",
        工号: "workNumber",
        部门: "departmentName",
      };
      // 按照字典顺序生成表头
      const header = Object.keys(dict);
      // console.log('表头',header);
      // 要将用户数组里面包裹的对象, 都变成数组
      const data = rows.map((user) => {
        return this.obj2arr(user, dict);
      });

      // 2. 生成excel
      export_json_to_excel({
        header,
        data,
      });
    },

    obj2arr(user, dict) {
      const newUser = [];
      // 中间这里写对象转数组逻辑
      // 因为表头是根据字典顺序生成的,
      // 所以用户数组的顺序也要一样
      // 于是遍历字典, 每遍历到一个, 就用当前的英文 key 去取值
      // 放入数组当中
      for (const key in dict) {
        const enKey = dict[key];
        const value = user[enKey];
        if (enKey === "formOfEmployment") {
          // 聘用形式的处理
          const obj = employeeEnum.hireType.find((v) => v.id === value);
          newUser.push(obj ? obj.value : "未知");
        } else if (enKey === "timeOfEntry" || enKey === "correctionTime") {
          // 时间的处理
          newUser.push(formatDate(value));
        } else {
          newUser.push(value);
        }
      }
      return newUser;
    },

    // 点击删除
    async delEmployee(id) {
      try {
        // 1. 二次询问
        await this.$confirm("你确定吗?");
        // 2. 发送请求
        await delEmployee(id);
        // 3. 提示用户
        this.$message.success("操作成功");
        // 4. 更新数据
        if (this.list.length === 1 && this.params.page > 1) {
          this.params.page--;
        }
        this.getEmployeeList();
      } catch (error) {}
    },
    showQRCode(imgUrl) {
      if (imgUrl) {
        this.isShowQRCode = true;
        setTimeout(() => {
          QRCode.toCanvas(this.$refs.myCanvas, imgUrl, {
            width: 300,
            color: {
              dark: "#66b1ff",
            },
          });
        }, 500);
      }
    },
    // 点击角色
    async assignRole(id) {
      await this.$refs.assignRole.getUserDetailById(id);
      this.userId = id;
      this.showRoleDialog = true;
    },
  },
};
</script>
<style scoped>
.avatar {
  width: 200px;
  height: 140px;
  /* 如果一张图片强制设置了宽高
  但是又不想改变比例 */
  object-fit: cover;
}
</style>